package com.sky.aop;

import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

//自动填充AOP(day03任务一)
@Component
@Slf4j
@Aspect
public class AutoFillAspect {

    @Before("@annotation(com.sky.aop.AutoFill)")
    public void autoFill(JoinPoint joinPoint){
        log.info("[自动填充中.....]");

        MethodSignature signature = (MethodSignature) joinPoint.getSignature();

        Method method = signature.getMethod();
        AutoFill annotation = signature.getMethod().getAnnotation(AutoFill.class);

        OperationType type = annotation.value();

        Object[] args = joinPoint.getArgs();
        if (args ==null || args.length==0){
            return;
        }
        Object dataPojo = args[0];
        log.info("[自动填充...] dataPojo 反射之前:{}",dataPojo);
        if (type==OperationType.INSERT){
            log.info("[自动填充...] method{} insert....",method.getName());
            try {
                Method setCreateUser = dataPojo.getClass().getDeclaredMethod("setCreateUser", Long.class);
                Method setCreateTime = dataPojo.getClass().getDeclaredMethod("setCreateTime", LocalDateTime.class);
                Method setUpdateUser = dataPojo.getClass().getDeclaredMethod("setUpdateTime", Long.class);
                Method setUpdateTime = dataPojo.getClass().getDeclaredMethod("setUpdateTime", LocalDateTime.class);

                setCreateUser.invoke(dataPojo, BaseContext.getCurrentId());
                setUpdateUser.invoke(dataPojo, BaseContext.getCurrentId());
                setCreateTime.invoke(dataPojo, LocalDateTime.now());
                setUpdateTime.invoke(dataPojo, LocalDateTime.now());
            } catch (Exception e) {
                e.printStackTrace();
                log.error("自动填充失败:{}", e.getMessage());
            }
        }else{
            log.info("[自动填充....] method:{} update....",method.getName());

            try{
                Method setUpdateUser = dataPojo.getClass().getDeclaredMethod("setUpdateTime", Long.class);
                Method setUpdateTime = dataPojo.getClass().getDeclaredMethod("setUpdateTime", LocalDateTime.class);

                setUpdateUser.invoke(dataPojo, BaseContext.getCurrentId());
                setUpdateTime.invoke(dataPojo,LocalDateTime.now());
            }catch (Exception e){
                e.printStackTrace();
                log.error("自动填充失败:{}",e.getMessage());
            }
            log.info("[自动填充....] dataPojo 反射之后:{}",dataPojo);
        }
    }
}
